package com.thread.sync.sync12;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    private Lock lock = new ReentrantLock();

    public void method01() {
        try {
            lock.lock();//加锁后,此线程将不会执行其他方法直到锁释放,与sync效果相同
            System.out.println("当前线程" + Thread.currentThread().getName() + "进入method01");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("当前线程" + Thread.currentThread().getName() + "进入退出method01");
            lock.unlock(); //使用重入锁必须在方法完成后释放锁
        }
    }

    ;

    public void method02() {
        try {
            lock.lock();
            System.out.println("当前线程" + Thread.currentThread().getName() + "进入method02");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("当前线程" + Thread.currentThread().getName() + "进入退出method02");
            lock.unlock();
        }
    }

    ;

    public static void main(String[] args) {
        TestLock te = new TestLock();
        new Thread(() -> {
            te.method01();
            te.method02();
        }, "t1").start();
    }
}
